package cn.wonderland.community.controller;

import cn.wonderland.community.service.IOwnerMemberService;
import cn.wonderland.community.domain.OwnerMember;
import cn.wonderland.community.query.OwnerMemberQuery;
import cn.wonderland.basic.util.AjaxResult;
import cn.wonderland.basic.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

import static cn.wonderland.community.util.GetAccessKey.getAccessKey;

@RestController
@RequestMapping("/ownerMember")
public class OwnerMemberController {
    @Autowired
    public IOwnerMemberService ownerMemberService;


    /**
     * 保存和修改公用的
     *
     * @param ownerMember 传递的实体
     * @return AjaxResult转换结果
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody OwnerMember ownerMember) {

        if (ownerMember.getId() != null) {
            ownerMemberService.update(ownerMember);
        } else {
            // 生成32位密钥编号
            String accessKey = getAccessKey();
            ownerMember.setAccessKey(accessKey);
            ownerMember.setCreateTime(new Date());
            Long id = ownerMember.getOwnerId();
            ownerMember.setOwnerId(id);
            ownerMemberService.add(ownerMember);
        }
        return AjaxResult.me().success();
    }

    /**
     * 删除对象信息
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {
        try {
            ownerMemberService.delete(id);
            return AjaxResult.me().success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().fail();
        }
    }

    //获取用户
    @GetMapping("/{id}")
    public OwnerMember get(@PathVariable("id") Long id) {
        return ownerMemberService.findById(id);
    }

    // 根据业主id 获取用户
    @GetMapping("/findByOwnerId/{id}")
    public List<OwnerMember> findByOwnerId(@PathVariable("id") Long id) {
        return ownerMemberService.findByOwnerId(id);
    }


    /**
     * 查看所有的员工信息
     *
     * @return
     */
    @GetMapping()
    public List<OwnerMember> list() {

        return ownerMemberService.findAll();
    }


    /**
     * 分页查询数据
     *
     * @param query 查询对象
     * @return PageList 分页对象
     */
    @PostMapping("/list")
    public PageList<OwnerMember> json(@RequestBody OwnerMemberQuery query) {
        return ownerMemberService.queryByPage(query);
    }
}
